#!/bin/bash

set -e
echo "准备开始升级内核"

KERNEL_VERSION=5.4.278
KERNEL_RPM="kernel-lt-$KERNEL_VERSION-1.el7.elrepo.x86_64.rpm"
DOWNLOAD_URL="https://mirrors.coreix.net/elrepo-archive-archive/kernel/el7/x86_64/RPMS/$KERNEL_RPM"

echo "下载Linux 内核"
echo "测试下载URL是否能通"
if [ ! -f "$KERNEL_RPM" ]; then
  if ! curl --output /dev/null --silent --head --fail "$DOWNLOAD_URL"; then
    echo "下载URL不通，退出脚本"
    exit 1
  fi
  echo "下载URL通畅，正在下载..."
  if ! wget -c "$DOWNLOAD_URL"; then
    echo "下载失败，退出脚本"
    exit 1
  fi
  echo "下载完成"
fi

echo "开始安装"
if ! rpm -ivh "$KERNEL_RPM"; then
  echo "安装失败，退出脚本"
  exit 1
fi
echo "安装完成"

echo "正在指定开机启动内核版本"
new_kernel_index=$(awk -F\' '$1=="menuentry " {print i++ " : " $2}' /etc/grub2.cfg | grep "$KERNEL_VERSION" | cut -d':' -f1 | head -n 1)
if [ -z "$new_kernel_index" ]; then
  echo "无法找到新安装的内核条目，退出脚本"
  exit 1
fi
grub2-set-default "$new_kernel_index"
echo "已指定开机启动内核版本"

echo "正在生成 grub 配置文件"
if ! grub2-mkconfig -o /boot/grub2/grub.cfg; then
  echo "生成grub配置文件失败，退出脚本"
  exit 1
fi
echo "已生成 grub 配置文件"

echo "内核已升级至 $KERNEL_VERSION，请重启机器生效."
